<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>wildcard</title>
</head>

<body>

</body>
<script>
  function find(source, pattern) {
    let starCount = 0;
    //遍历目标字符串有没有*
    for (let i = 0; i < pattern.length; i++) {
      if (pattern[i] === '*')
        starCount++;
    }
    //如果没有*，只要目标字符串与源字符串存在不一样 且不是？就直接返回false
    if (starCount === 0) {
      for (let i = 0; i < pattern.length; i++) {
        if (pattern[i] !== source[i] && pattern[i] !== '?') {
          return false;
        }
        return;
      }
    }

    let i = 0;
    let lastIndex = 0;
    //pattern[i]不是*，只要不匹配source[i],并且也不是？ 直接返回false
    for (i = 0; pattern[i] !== '*'; i++) {
      if (pattern[i] !== source[i] && pattern[i] !== '?') {
        return false
      }
    }
    lastIndex = i;
    for (let p = 0; p < starCount - 1; p++) {
      i++;
      let subPattern = ''
      while (pattern[i] !== '*') {
        subPattern += pattern[i];
        i++;
      }
      let reg = new RegExp(subPattern.replace(/\?/g, '[\\s\\S]'), 'g');
      reg.lastIndex = lastIndex;
      //这里不能有console.log(reg.exec(source))，因为会改变源字符串，后面就会报错
      // console.log(reg.exec(source))
      if (!reg.exec(source)) {
        return false
      }
    }

    for (let j = 0; j < source.length - lastIndex && pattern[pattern.length - j] !== '*'; j++) {
      if (pattern[pattern.length - j] !== source[source.length - j] && pattern[pattern.length - j] !== '?') {
        return false
      }
    }
    return true
  }
  console.log(find('abcabcabxaac', 'a*b*bx*c'))
</script>

</html>